<template>
  <el-dialog
    title="考核组成管理"
    v-model="visible"
    width="800px"
    :before-close="handleClose"
  >
    <div class="exam-parts-container">
      <div class="header-info" v-if="teachingMission">
        <h3>课程：{{ teachingMission.courseName }}</h3>
        <p>学期：{{ teachingMission.termName }}</p>
      </div>
      
      <el-alert
        v-if="examParts.length === 0"
        title="尚未设置考核组成部分，请使用下方表单添加"
        type="info"
        :closable="false"
        show-icon
      />
      
      <el-table
        v-if="examParts.length > 0"
        :data="examParts"
        border
        style="width: 100%; margin-bottom: 20px;"
      >
        <el-table-column prop="name" label="考核部分名称" min-width="120" />
        <el-table-column prop="proportion" label="比例%" width="80">
          <template #default="scope">
            <span>{{ scope.row.proportion }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="scoreTypeName" label="评分类型" width="120" />
        <el-table-column label="考核性质" width="180">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.examPartType === 'FORMATIVE' || scope.row.isFormative" 
              type="success" 
              size="small" 
              effect="plain" 
              style="margin-right: 5px;"
            >
              形成性
            </el-tag>
            <el-tag 
              v-if="scope.row.examPartType === 'FINAL' || scope.row.isFinal" 
              type="warning" 
              size="small" 
              effect="plain"
            >
              终结性
            </el-tag>
            <el-tag 
              v-if="scope.row.examPartType === 'OTHER'" 
              type="info" 
              size="small" 
              effect="plain"
            >
              其它
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeExamPart(scope.$index)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="total-proportion" v-if="examParts.length > 0">
        <el-progress 
          :percentage="totalProportion" 
          :status="totalProportion === 100 ? 'success' : ''" 
          :stroke-width="20"
          :format="(percentage) => `总比例: ${percentage}%`"
        />
      </div>
      
      <el-divider content-position="center">添加考核组成部分</el-divider>
      
      <el-form ref="examPartFormRef" :model="examPartForm" :rules="rules" label-width="120px">
        <el-form-item label="考核部分名称" prop="name">
          <el-input v-model="examPartForm.name" placeholder="如：平时成绩、期末考试" />
        </el-form-item>
        
        <el-form-item label="比例(%)" prop="proportion">
          <el-input-number 
            v-model="examPartForm.proportion" 
            :min="1" 
            :max="100"
            :step="5"
            controls-position="right"
          />
        </el-form-item>
        
        <el-form-item label="评分类型" prop="scoreTypeId">
          <el-select v-model="examPartForm.scoreTypeId" placeholder="选择评分类型">
            <el-option 
              v-for="type in scoreTypes" 
              :key="type.id" 
              :label="type.name" 
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="考核性质">
          <el-select v-model="examPartForm.examPartType" placeholder="请选择考核类型">
            <el-option label="形成性考核" value="FORMATIVE" />
            <el-option label="终结性考核" value="FINAL" />
            <el-option label="其它" value="OTHER" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="addExamPart">添加</el-button>
          <el-button @click="resetExamPartForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <div class="left-actions">
          <el-button 
            type="success" 
            @click="handleBatchCopy"
            :disabled="examParts.length === 0 || totalProportion !== 100"
            plain
          >
            <el-icon><DocumentCopy /></el-icon>
            批量复制
          </el-button>
          <el-button 
            type="primary" 
            @click="handleCrossTermCopy"
            :disabled="examParts.length === 0 || totalProportion !== 100"
            plain
          >
            <el-icon><Switch /></el-icon>
            跨学期复制
          </el-button>
          <el-button 
            type="warning" 
            @click="handleBatchSet"
            plain
          >
            <el-icon><Setting /></el-icon>
            批量设置
          </el-button>
        </div>
        <div class="right-actions">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="saveExamParts" :disabled="examParts.length === 0 || totalProportion !== 100">
            保存
          </el-button>
        </div>
      </span>
    </template>
  </el-dialog>

  <!-- 批量复制对话框 -->
  <ExamPartsCopyDialog
    v-model:visible="copyDialogVisible"
    :source-mission="teachingMission"
    @copy-success="handleCopySuccess"
  />
  
  <!-- 跨学期复制对话框 -->
  <CrossTermCopyDialog
    v-model:visible="crossTermCopyDialogVisible"
    :source-mission-id="teachingMission?.id"
    @completed="handleCrossTermCopySuccess"
  />
  
  <!-- 批量设置对话框 -->
  <BatchSetExamPartsDialog
    v-model:visible="batchSetDialogVisible"
    @completed="handleBatchSetSuccess"
  />
</template>

<script>
import { ref, computed, onMounted, reactive, watchEffect, watch } from 'vue'
import { Delete, DocumentCopy, Switch, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { courseExamPartApi, courseExamPartApiExt } from '@/api/course-exam-part'
import ExamPartsCopyDialog from './ExamPartsCopyDialog.vue'
import CrossTermCopyDialog from './CrossTermCopyDialog.vue'
import BatchSetExamPartsDialog from './BatchSetExamPartsDialog.vue'

export default {
  name: 'ExamPartsDialog',
  components: {
    Delete,
    DocumentCopy,
    Switch,
    Setting,
    ExamPartsCopyDialog,
    CrossTermCopyDialog,
    BatchSetExamPartsDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    teachingMission: {
      type: Object,
      required: true
    }
  },
  emits: ['update:modelValue', 'saved'],
  
  setup(props, { emit }) {
    // 对话框可见性
    const visible = computed({
      get: () => props.modelValue,
      set: (val) => emit('update:modelValue', val)
    })
    
    // 考核组成部分列表
    const examParts = ref([])
    
    // 评分类型列表
    const scoreTypes = ref([])
    
    // 表单引用和数据
    const examPartFormRef = ref(null)
    const examPartForm = reactive({
      name: '',
      proportion: 30,
      scoreTypeId: null,
      examPartType: 'FORMATIVE' // 默认为形成性考核
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入考核部分名称', trigger: 'blur' },
        { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
      ],
      proportion: [
        { required: true, message: '请输入比例', trigger: 'change' },
        { type: 'number', min: 1, max: 100, message: '比例必须在1-100之间', trigger: 'change' }
      ],
      scoreTypeId: [
        { required: true, message: '请选择评分类型', trigger: 'change' }
      ]
    }
    
    // 计算总比例
    const totalProportion = computed(() => {
      return examParts.value.reduce((sum, part) => sum + part.proportion, 0)
    })
    
    // 获取所有评分类型
    const fetchScoreTypes = async () => {
      try {
        // 假设有获取所有评分类型的API
        // 这里临时模拟数据
        scoreTypes.value = [
          { id: 1, name: '百分制' },
          { id: 2, name: '五级制(优良中及格不及格)' },
          { id: 3, name: '二级制(通过/不通过)' }
        ]
        
        // 设置默认值
        if (scoreTypes.value.length > 0) {
          examPartForm.scoreTypeId = scoreTypes.value[0].id
        }
      } catch (error) {
        console.error('获取评分类型失败:', error)
        ElMessage.error('获取评分类型失败')
      }
    }
    
    // 获取教学任务的考核组成部分
    const fetchExamParts = async () => {
      if (!props.teachingMission || !props.teachingMission.id) {
        examParts.value = [];
        return;
      }
      
      try {
        const response = await courseExamPartApi.getExamPartsByTeachingMission(props.teachingMission.id)
        examParts.value = response || []
      } catch (error) {
        console.error('获取考核组成部分失败:', error)
        ElMessage.error('获取考核组成部分失败')
        examParts.value = [];
      }
    }
    
    // 添加考核组成部分
    const addExamPart = () => {
      examPartFormRef.value.validate(async (valid) => {
        if (valid) {
          // 检查教学任务是否有效
          if (!props.teachingMission || !props.teachingMission.id) {
            ElMessage.warning('教学任务信息不完整，无法添加考核部分')
            return
          }
          
          // 检查名称是否重复
          const existingPart = examParts.value.find(part => part.name === examPartForm.name)
          if (existingPart) {
            ElMessage.warning('已存在相同名称的考核部分')
            return
          }
          
          // 检查添加后总比例是否超过100%
          const newTotalProportion = totalProportion.value + examPartForm.proportion
          if (newTotalProportion > 100) {
            ElMessage.warning(`添加后总比例将超过100%，请调整比例`)
            return
          }
          
          // 获取选中的评分类型名称
          const selectedScoreType = scoreTypes.value.find(type => type.id === examPartForm.scoreTypeId)
          
          // 构建新的考核部分对象
          const newPart = {
            name: examPartForm.name,
            proportion: examPartForm.proportion,
            scoreTypeId: examPartForm.scoreTypeId,
            scoreTypeName: selectedScoreType ? selectedScoreType.name : '',
            examPartType: examPartForm.examPartType,
            // 为了兼容，同时设置旧字段
            isFormative: examPartForm.examPartType === 'FORMATIVE',
            isFinal: examPartForm.examPartType === 'FINAL',
            teachingMissionId: props.teachingMission.id
          }
          
          // 添加到列表
          examParts.value.push(newPart)
          
          // 重置表单
          resetExamPartForm()
          
          ElMessage.success('考核部分添加成功')
        }
      })
    }
    
    // 移除考核组成部分
    const removeExamPart = (index) => {
      ElMessageBox.confirm('确定要删除该考核组成部分吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        examParts.value.splice(index, 1)
        ElMessage.success('考核部分删除成功')
      }).catch(() => {})
    }
    
    // 保存所有考核组成部分
    const saveExamParts = async () => {
      if (examParts.value.length === 0) {
        ElMessage.warning('请至少添加一个考核组成部分')
        return
      }
      
      if (totalProportion.value !== 100) {
        ElMessage.warning(`所有考核部分的总比例必须为100%，当前为${totalProportion.value}%`)
        return
      }
      
      // 检查教学任务是否有效
      if (!props.teachingMission || !props.teachingMission.id) {
        ElMessage.warning('教学任务信息不完整，无法保存考核部分')
        return
      }
      
      try {
        await courseExamPartApiExt.saveExamParts(props.teachingMission.id, examParts.value)
        ElMessage.success('考核组成保存成功')
        emit('saved')
        visible.value = false
      } catch (error) {
        console.error('保存考核组成部分失败:', error)
        ElMessage.error('保存考核组成部分失败')
      }
    }
    
    // 重置表单
    const resetExamPartForm = () => {
      examPartFormRef.value.resetFields()
      examPartForm.examPartType = 'FORMATIVE'
    }
    
    // 关闭对话框
    const handleClose = () => {
      if (examParts.value.length > 0 && !confirm('关闭将丢失未保存的更改，确定关闭吗？')) {
        return
      }
      visible.value = false
    }
    
    // 监听教学任务变化，重新加载考核组成部分
    watchEffect(() => {
      if (visible.value && props.teachingMission && props.teachingMission.id) {
        fetchExamParts()
      }
    })
    
    // 批量复制相关状态
    const copyDialogVisible = ref(false)
    
    // 跨学期复制相关状态
    const crossTermCopyDialogVisible = ref(false)
    
    // 批量设置相关状态
    const batchSetDialogVisible = ref(false)
    
    // 处理批量复制
    const handleBatchCopy = () => {
      if (examParts.value.length === 0) {
        ElMessage.warning('当前没有考核组成部分可复制')
        return
      }
      
      if (totalProportion.value !== 100) {
        ElMessage.warning(`考核组成比例不完整（当前${totalProportion.value}%），请先完善考核方案后再复制`)
        return
      }
      
      copyDialogVisible.value = true
    }
    
    // 处理跨学期复制
    const handleCrossTermCopy = () => {
      if (examParts.value.length === 0) {
        ElMessage.warning('当前没有考核组成部分可复制')
        return
      }
      
      if (totalProportion.value !== 100) {
        ElMessage.warning(`考核组成比例不完整（当前${totalProportion.value}%），请先完善考核方案后再复制`)
        return
      }
      
      crossTermCopyDialogVisible.value = true
    }
    
    // 处理批量设置
    const handleBatchSet = () => {
      batchSetDialogVisible.value = true
    }
    
    // 处理复制成功回调
    const handleCopySuccess = (copiedCount) => {
      ElMessage.success(`成功复制考核方案到 ${copiedCount} 个教学任务`)
      copyDialogVisible.value = false
    }
    
    // 处理跨学期复制成功回调
    const handleCrossTermCopySuccess = () => {
      ElMessage.success('跨学期复制考核方案成功')
      crossTermCopyDialogVisible.value = false
    }
    
    // 处理批量设置成功回调
    const handleBatchSetSuccess = () => {
      ElMessage.success('批量设置考核组成成功')
      batchSetDialogVisible.value = false
    }
    
    // 监听对话框显示状态变化
    watch(visible, (newVisible) => {
      if (newVisible && props.teachingMission && props.teachingMission.id) {
        fetchExamParts()
      }
    })
    
    onMounted(() => {
      fetchScoreTypes()
      if (props.teachingMission && props.teachingMission.id && visible.value) {
        fetchExamParts()
      }
    })
    
    return {
      visible,
      examParts,
      scoreTypes,
      examPartFormRef,
      examPartForm,
      rules,
      totalProportion,
      addExamPart,
      removeExamPart,
      saveExamParts,
      resetExamPartForm,
      handleClose,
      // 批量复制相关
      copyDialogVisible,
      handleBatchCopy,
      handleCopySuccess,
      // 跨学期复制相关
      crossTermCopyDialogVisible,
      handleCrossTermCopy,
      handleCrossTermCopySuccess,
      // 批量设置相关
      batchSetDialogVisible,
      handleBatchSet,
      handleBatchSetSuccess
    }
  }
}
</script>

<style scoped>
.exam-parts-container {
  margin-bottom: 20px;
}

.header-info {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.header-info h3 {
  margin: 0 0 5px 0;
  font-size: 18px;
}

.header-info p {
  margin: 0;
  color: #666;
}

.total-proportion {
  margin: 15px 0;
}

.el-divider {
  margin: 24px 0;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.left-actions {
  flex: 0 0 auto;
}

.right-actions {
  flex: 0 0 auto;
}

.left-actions .el-button {
  margin-right: 0;
}

.right-actions .el-button {
  margin-left: 8px;
}
</style>
